package com.assets.Login;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;

import android.os.Handler;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.assets.Ip_set.Url;
import com.assets.R;
import com.assets.menu.SlideSideMenuExampleActivity;
import com.assets.newNHF.util.LogUtils;
import com.assets.util.MyOkHttp;
import com.assets.util.NetworkUtil;
import com.assets.util.Since_case;
import com.assets.util.SpUtils;
import com.hb.dialog.dialog.LoadingDialog;
import com.hb.dialog.myDialog.MyAlertInputDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.functions.Function;
import io.reactivex.rxjava3.schedulers.Schedulers;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * Created by Administrator on 2018/12/26.
 */

public class login extends Activity {
    private EditText et_user;

    private float versionCode = 0;
    private EditText et_password;
    private int i = 0;
    private SharedPreferences jz;
    private String url;
    LoadingDialog loadingDialog;
    private CheckBox checkBox;
    private Context context;



    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_logo_activty);
//        getVersion();
//        getAPKVersion();
//        if (SpUtils.getInstance().getBoolean("isToken")) {
//            Intent intent = new Intent(login.this, SlideSideMenuExampleActivity.class);
//            startActivity(intent);
//        }


        context = this;
        SharedPreferences mm = getSharedPreferences("mm", Context.MODE_PRIVATE);//1.通过上下文得到
        String ipip = mm.getString("ipip", "");
        if (!ipip.equals("")) {
            Url ipSet = new Url();
            ipSet.setIP(ipip);
        }
        url = Url.http() + Url.IP + "/api/login";
        initView();
        Log.i("ipipip", Url.IP);
        String yy = mm.getString("b", "");
        if (yy.equals("1")) {
            checkBox.setChecked(true);
            et_user.setText(mm.getString("user", ""));
            et_password.setText(mm.getString("password", ""));
        } else if (yy.equals("0")) {
            checkBox.setChecked(false);
            et_user.setText("");
            et_password.setText("");
        }
        checkBox.setOnCheckedChangeListener((compoundButton, b) -> {
            if (checkBox.isChecked()) {
                jz = getSharedPreferences("mm", Context.MODE_PRIVATE);//1.通过上下文得到
                SharedPreferences.Editor editor = jz.edit();  //2.通过SharedPreferences得到编辑器用于保存数据
                editor.putString("user", et_user.getText().toString());
                editor.putString("password", et_password.getText().toString()); //3.键值对的形式保存数据
                editor.putString("b", "1");
                editor.commit();
            } else {
                jz = getSharedPreferences("mm", Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = jz.edit();
                editor.putString("b", "0");
                editor.commit();
            }
        });
    }

    private void Login(final String user, final String password) {
        Log.i("ipipip", Url.IP);
        Map<String, String> map = new HashMap<>();
        map.put("account", user);
        map.put("password", password);
        MyOkHttp.getInstance().post(url, map, new MyOkHttp.requestMessage() {
            @Override
            public void requestFail() {
                showToast("连接服务器失败");
            }

            @Override
            public void requestComplete() {
                dismiss();
            }

            @Override
            public void requestSuccess(Response response) throws IOException {
                String responseData = response.body().string();
                try {
                    LogUtils.d(responseData);
                    JSONObject json = new JSONObject(responseData);
                    String state = json.optString("state");
                    if (state.equals("1")) {
                        JSONObject jsonObject = json.optJSONObject("user");
                        jz = getSharedPreferences("mm", Context.MODE_PRIVATE);//1.通过上下文得到
                        SharedPreferences.Editor editor = jz.edit();  //2.通过SharedPreferences得到编辑器用于保存数据
//                        if (jsonObject == null) {
//                            showToast("用户信息为空");
//                            return;
//                        }
                        String userId = jsonObject.optString("userId");
//                        if (TextUtils.isEmpty(userId)) {
//                            showToast("用户id为空");
//                            return;
//                        }
                        String roleid = jsonObject.optString("roleId");
//                        if (TextUtils.isEmpty(roleid)) {
//                            showToast("角色id为空");
//                            return;
//                        }
                        String deptId = jsonObject.optString("deptId");
//                        if (TextUtils.isEmpty(deptId)) {
//                            showToast("部门id为空");
//                            return;
//                        }
                        String name = jsonObject.optString("name");
//                        if (TextUtils.isEmpty(name)) {
//                            showToast("用户名称为空");
//                            return;
//                        }
                        String company = json.optString("company");
//                        if (TextUtils.isEmpty(company)) {
//                            showToast("用户公司为空");
//                            return;
//                        }
                        String data = jsonObject.optString("data");
//                        if (TextUtils.isEmpty(data)) {
//                            showToast("用户未分配数据权限");
//                            return;
//                        }
                        Since_case.getInstance().setData(data);
                        Since_case.getInstance().setUserId(userId);
                        Since_case.getInstance().setRoleId(roleid);
                        Since_case.getInstance().setDeptId(deptId);
                        Since_case.getInstance().setName(name);
                        Since_case.getInstance().setCompany(company);
                        editor.putString("roleid", roleid);
                        editor.putString("deptid", deptId);
                        editor.putString("name", name);
                        editor.putString("user", user);
                        editor.putString("password", password); //3.键值对的形式保存数据
                        editor.apply();
                        Intent intent = new Intent(login.this, SlideSideMenuExampleActivity.class);
                        SpUtils.getInstance().putBoolean("isToken", true);
                        SpUtils.getInstance().putString("userId", userId);
                        startActivity(intent);
                    }
                    if (state.equals("0")) {
                        showToast("账号或密码错误");
                        return;
                    }
                    if (state.equals("500")) {
                        showToast("服务器异常");
                    }
                } catch (JSONException e) {
                    showToast("解析异常");
                    e.printStackTrace();
                }
            }
        });

    }

    private void dismiss() {
        if (loadingDialog != null && loadingDialog.isShowing()) {
            runOnUiThread(() -> loadingDialog.dismiss());
        }
    }


    private void initView() {
        et_user = (EditText) findViewById(R.id.et_userName);
        et_password = (EditText) findViewById(R.id.et_password);
        checkBox = (CheckBox) findViewById(R.id.cb_checkbox);
        TextView setIp = (TextView) findViewById(R.id.setip);
        Button login = (Button) findViewById(R.id.btn_login);
        setIp.setOnClickListener(v -> {
            final MyAlertInputDialog myAlertInputDialog = new MyAlertInputDialog(login.this).builder()
                    .setTitle("修改IP地址")
                    .setEditText(Url.IP);
            myAlertInputDialog.setPositiveButton("确认", v1 -> {
                jz = getSharedPreferences("mm", Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = jz.edit();
                editor.putString("ipip", myAlertInputDialog.getResult());
                editor.apply();
                Url ipSet = new Url();
                ipSet.setIP(myAlertInputDialog.getResult());
                url = Url.http() + Url.IP + "/api/login";
                myAlertInputDialog.dismiss();
                Log.i("ipipip", Url.IP);
            }).setNegativeButton("取消", v12 -> myAlertInputDialog.dismiss());
            myAlertInputDialog.show();
        });
        login.setOnClickListener(v -> {
            String user = et_user.getText().toString();
            String password = et_password.getText().toString();
            if (TextUtils.isEmpty(user) || TextUtils.isEmpty(password)) {
                showToast("账号或密码不准为空");
                return;
            }
            loadingDialog = new LoadingDialog(login.this);
            loadingDialog.setMessage("正在登录....");
            if (!loadingDialog.isShowing()) {
                loadingDialog.show();
            }
            Login(user, password);

        });
    }

    private long mExitTime;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        //判断用户是否点击了“返回键”
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            //与上次点击返回键时刻作差
            if ((System.currentTimeMillis() - mExitTime) > 2000) {//2000毫秒
                //大于2000ms则认为是误操作，使用Toast进行提示
                showToast("再按一次退出");
                //并记录下本次点击“返回键”的时刻，以便下次进行判断
                mExitTime = System.currentTimeMillis();//上次点击时间
            } else {
                //小于2000ms则认为是用户确实希望退出程序-调用System.exit()方法进行退出
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void showToast(final String msg) {
        runOnUiThread(() -> Toast.makeText(context, msg, Toast.LENGTH_SHORT).show());
    }

}
